import mongoose from 'mongoose'
import { Models } from '../../common/typings/model'
import { DataBaseFailed } from '../../core/HttpException'
import MongoDB from '../../core/MongoDB'
type ColType = 48 | 32 | 16 // 48 日期,32 number, 16 string

interface Fields {
  name: string
  type: ColType
  transferName: string
}

interface DataSource {
  name: string
  fields: Fields[]
  data: Date
}

interface Command {
  [propName: string]: any
}

class DataSourceDB extends MongoDB {
  public static Model: mongoose.Model<DataSource> = this.init()
  private static init() {
    const Schema = mongoose.Schema
    const dataSourceSchema = new Schema({
      name: String,
      fields: Array,
      data: Date,
    })
    return mongoose.model('data_source', dataSourceSchema)
    // this.model = new this.Model()
  }
  /*
   * 数据库增删改查
   * @param command 增删改查语句
   * @param value 对应的值
   */
  public static async command(command: Command, value?: Array<any>): Promise<Models.Result> {
    try {
      return new Promise<Models.Result>(async (resolve, reject) => {
        this.Model.find(command, (error: Error) => {
          //console.log(error,connection)
          if (error) {
            const result = {
              error,
              msg: '数据库连接出错' + ':' + (error as Error)?.message,
            }

            reject(result)
            return result
          }
          // console.log(model)
          const result: Models.Result = {
            msg: 'ok',
            state: 1,
            results: [],
            // results: model.map(Utils.lineToHumpObject)
          }
          resolve(result)
        })
      })
    } catch (err) {
      // console.log(command)
      throw new DataBaseFailed()
    }
  }
}

const DataSource = DataSourceDB.Model

export default DataSourceDB
